package com.cz.czchat;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.cz.R;
import com.cz.utils.Config;
import com.cz.utils.Utils;
import com.cz.widget.DemoHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {
    private View mView;
    private Button backBtn;
    private Button registerBtn;
    private EditText userNameText;
    private EditText passwordOne;
    private EditText passwordTwo;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case Config.REGISTER_STATE_SUCCESS:
                    Toast.makeText(RegisterActivity.this, "注册成功返回登录", Toast.LENGTH_SHORT).show();
                    RegisterActivity.this.finish();
                    break;
                case Config.REGISTER_STATE_FAIL:
                    Log.i("TAG","register fail");
                    Toast.makeText(RegisterActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initView();
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.back:
                    RegisterActivity.this.finish();
                    break;
                case R.id.register_button:
                    String username = userNameText.getText().toString();
                    String password1 = passwordOne.getText().toString();
                    String password2 = passwordTwo.getText().toString();
                    if (TextUtils.isEmpty(username) | TextUtils.isEmpty(password1) | TextUtils.isEmpty(password2)) {
                        Toast.makeText(RegisterActivity.this, "输入不能为空", Toast.LENGTH_SHORT).show();
                    } else if (!password1.equals(password2)) {
                        Toast.makeText(RegisterActivity.this, "两次输入密码不一致", Toast.LENGTH_SHORT).show();
                    } else {
                        Log.i("TAG","do register");
                        try {
                            Register(username, password1);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

            }
        }
    };

    private void initView() {
        mView = findViewById(R.id.view);
        int result = 0;
        int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = this.getResources().getDimensionPixelSize(resourceId);
        }
        int stateHigh = 0;

        if (Utils.hasNotchAtHuawei(this)) {
            stateHigh = Utils.getNotchSizeAtHuawei(RegisterActivity.this)[1];
        }
        if (Utils.hasNotchAtOPPO(RegisterActivity.this)) {
            stateHigh = 80;
        }
        if (Utils.hasNotchAtVivo(RegisterActivity.this)) {
            stateHigh = Utils.dip2px(RegisterActivity.this, 27);
        }
        if (Utils.hasNotchAtMI(RegisterActivity.this)) {
            stateHigh = 89;
        }

        if (stateHigh > result) {
            result = stateHigh;
        }
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, result);
        mView.setBackgroundColor(Color.parseColor("#1e90ff"));
        mView.setLayoutParams(params);
        Utils.translucentStatusBar(RegisterActivity.this, true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        backBtn = findViewById(R.id.back);
        registerBtn = findViewById(R.id.register_button);
        userNameText = findViewById(R.id.username);
        passwordOne = findViewById(R.id.password1);
        passwordTwo = findViewById(R.id.password2);
        backBtn.setOnClickListener(mOnClickListener);
        registerBtn.setOnClickListener(mOnClickListener);
    }

    private void Register(String username, String password) throws JSONException {
        String url = Config.HX_SERVER + "/" + Config.ORG_name + "/" + Config.APP_NAME + "/" + Config.REGISTER_actions;
        Log.i("TAG",url);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient.Builder().build();
        JSONObject json = new JSONObject();
        json.put("username",username);
        json.put("password", password);
        json.put("nickname", username);
        RequestBody body = RequestBody.create(JSON,json.toString());

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("TAG", "register fail1");
                Message msg = new Message();
                msg.what = Config.REGISTER_STATE_FAIL;
                msg.obj = e.getMessage();
                mHandler.sendMessage(msg);

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message msg = new Message();
                String result = response.body().string();
                Log.i("TAG", result);
                try {
                    JSONObject obj = new JSONObject(result);
                    if (obj.has("error")){
                        msg.what = Config.REGISTER_STATE_FAIL;
                        msg.obj = "用户名已存在";
                        mHandler.handleMessage(msg);
                        Toast.makeText(RegisterActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (response.code() == 400) {
                    msg.what = Config.REGISTER_STATE_FAIL;
                    msg.obj = "用户名已存在";
                    mHandler.handleMessage(msg);
                } else if (response.code() == 200) {
                    DemoHelper.getInstance().setCurrentUserName(username);
                    msg.what = Config.LOGIN_STATE_SUCCESS;
                    mHandler.sendMessage(msg);
                }
            }
        });
    }

}
